//
//  InboxViewController.m
//  HotWord
//
//  Created by Ji Qi on 12-6-30.
//  Copyright (c) 2012年 __MyCompanyName__. All rights reserved.
//

#import "InboxViewController.h"
#import "ConversationViewController.h"
#import "MessageManager.h"
#import "UserManager.h"
#import "FriendInfoViewController.h"
#import "UserInfoViewController.h"
#import "SliderBtn.h"


@interface InboxViewController ()

@end

@implementation InboxViewController
@synthesize dialogTableView;
@synthesize backBtn;
@synthesize noDataView;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}


- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.dialogTableView.top = self.view.height;
    self.backBtn.alpha = 0;
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(receiveMessageNotification) name:NOTIFICATION_RECEIVE_MESSAGE object:nil];
    
    SliderBtn *sliderBtn = (SliderBtn *)[[[NSBundle mainBundle] loadNibNamed:@"SliderBtn" owner:self options:nil] objectAtIndex:0];
    sliderBtn.tag = 111;
    [self.view addSubview:sliderBtn];
}

- (void)receiveMessageNotification
{
    if (_messages) {
        [_messages release];
        _messages = nil;
    }
    _messages = [[[MessageManager sharedManager] getLastestMessages] retain];
    [self.dialogTableView reloadData];
    if ([_messages count] <=0) {
        self.noDataView.hidden = NO;
    }
    else {
        self.noDataView.hidden = YES;
    }
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self receiveMessageNotification];
    if (![APP_DELEGATE.touchMaskView isDescendantOfView:self.view])
    {
        [self.view insertSubview:APP_DELEGATE.touchMaskView belowSubview:[self.view viewWithTag:111]];
    }
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    [UIView animateWithDuration:0.5 
                     animations:^{
                         self.backBtn.alpha = 1;
                         self.dialogTableView.top = 0;
                     }];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [UIView animateWithDuration:0.3 
                     animations:^{
                         self.backBtn.alpha = 0;
                     }];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{

    static NSString *CellIdentifier = @"InboxCell";
    
    InboxCell *cell = (InboxCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    if (cell == nil) {
        cell = [[[NSBundle mainBundle] loadNibNamed:@"InboxCell" owner:self options:nil] objectAtIndex:0];
    }
    [cell setMessageForCell:[_messages objectAtIndex:indexPath.row]];
    cell.indexPath = indexPath;
    cell.delegate = self;
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{

    return 100;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return [_messages count];
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    InboxCell *inboxCell = (InboxCell *)[tableView cellForRowAtIndexPath:indexPath];
    if (inboxCell.isDeleting) {
        return;
    }
    
    User *user = [[[User alloc] init] autorelease];
    
    if ([inboxCell.message.senderUserId isEqualToString:[UserManager sharedManager].currentUser.userId]) {
        user.userId = inboxCell.message.recevierUserId;
    }
    else {
        user.userId = inboxCell.message.senderUserId;
    }
    
    user.email = inboxCell.message.dialogEmail;
    user.avater = inboxCell.message.dialogAvator;
    user.nickname = inboxCell.message.dialogNickname;
    ConversationViewController *conversationViewController = [[[ConversationViewController alloc] initWithUser:user] autorelease];
    [self.navigationController pushViewController:conversationViewController animated:YES];
}

- (void)viewDidUnload
{
    [self setDialogTableView:nil];
    [self setBackBtn:nil];
    [self setNoDataView:nil];
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

- (IBAction)tapOnBackBtn:(id)sender {
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)InboxCellDidDelete:(InboxCell *)inboxCell
{
    NSString *userId;
    Message *message = inboxCell.message;
    if ([[UserManager sharedManager].currentUser.userId isEqualToString:message.senderUserId]) {
        userId = message.recevierUserId;
    }
    else {
        userId = message.senderUserId;
    }
    [[MessageManager sharedManager] removeMessageByUserId:userId];
    NSInteger messageIndex = [_messages indexOfObject:message];
    [_messages removeObjectAtIndex:messageIndex];
    NSMutableArray *deleteCells = [NSMutableArray arrayWithObject:[NSIndexPath indexPathForRow:messageIndex inSection:0]];
    [self.dialogTableView deleteRowsAtIndexPaths:deleteCells withRowAnimation:UITableViewRowAnimationRight];
    
    if ([_messages count] <=0) {
        self.noDataView.hidden = NO;
    }
    else {
        self.noDataView.hidden = YES;
    }
}

- (void)InboxHeaderDidSelected:(InboxCell *)inboxCell
{
    if (inboxCell.isDeleting) {
        return;
    }
    User *user = [[[User alloc] init] autorelease];
    if ([inboxCell.message.senderUserId isEqualToString:[UserManager sharedManager].currentUser.userId]) {
        user.userId = inboxCell.message.recevierUserId;
    }
    else {
        user.userId = inboxCell.message.senderUserId;
    }
    user.email = inboxCell.message.dialogEmail;
    user.avater = inboxCell.message.dialogAvator;
    user.nickname = inboxCell.message.dialogNickname;
//    FriendInfoViewController *friendInfoViewController = [[[FriendInfoViewController alloc] initWithUser:user] autorelease];
//    [self.navigationController pushViewController:friendInfoViewController animated:YES];
    UserInfoViewController *userInfoViewController = [[[UserInfoViewController alloc] initWithUser:user] autorelease];
    [self.navigationController pushViewController:userInfoViewController animated:YES];

}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    [_messages release];
    [dialogTableView release];
    [backBtn release];
    [noDataView release];
    [super dealloc];
}
@end
